package com.example.iceman.stepcounterapp;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;

import com.example.iceman.stepcounterapp.db.StepDataBase;

import java.util.ArrayList;
import java.util.Calendar;

/**
 * Created by iceman on 16/3/11 11:06
 * 邮箱：xubin865@pingan.com.cn
 */
public class StepCountService extends Service {
    private NewStepCounter stepCounter;
    private int steps;
    private int totalSteps;
    private String name;
    private String token;
    private final String STEP_CACHE_KEY = "step_cache";
    private StepSaveManager stepSaveManager;

    private BroadcastReceiver timeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("时间变化");
            Calendar calendar = Calendar.getInstance();
            if (calendar.get(Calendar.MINUTE) == 0) {//每个整点进行步数统计
//            if (calendar.get(Calendar.SECOND) == 0) {//test_每个整分进行步数统计
                if (steps > 10) {
                    String year = String.valueOf(calendar.get(Calendar.YEAR));
                    String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
                    String week = String.valueOf(calendar.get(Calendar.WEEK_OF_YEAR));
                    String day = String.valueOf(calendar.get(Calendar.DAY_OF_YEAR));
                    String dayInMonth = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
                    String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
//                    String hour = String.valueOf(calendar.get(Calendar.MINUTE));
                    saveHourStep(year, month, week, day, dayInMonth, hour, steps);
                }
                steps = 0;
                uploadStep();
            }

        }
    };

    /**
     * 整点时保存步行记录到数据库中
     */
    private void saveHourStep(String year, String month, String week, String day, String dayInMonth, String hour, int count) {

        StepDataBase entity = new StepDataBase();
        entity.count = steps;
        entity.year = year;
        entity.month = month;
        entity.week = week;
        entity.day = day;
        entity.dayInMonth = dayInMonth;
        entity.hour = hour;
        stepSaveManager.insertStepRecord(entity);
        steps = 0;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        readSaveData();
        stepCounter = new NewStepCounter(this);
        stepCounter.setOnStepListener(new StepChangeListener() {
            @Override
            public void onStep(int orientation) {
                System.out.println("StepCountService:onStep");
                steps++;
                totalSteps++;
            }

            @Override
            public void onLog(String log) {

            }
        });
        stepCounter.start();
        steps = SharePreferencesUtil.getInt(STEP_CACHE_KEY, 0);
        stepSaveManager = StepSaveManager.getInstance();
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_TIME_TICK);
        registerReceiver(timeReceiver, intentFilter);
    }

    /**
     * 被杀掉以后,要重新获得usertoken.
     */
    private void readSaveData() {
        String saveData = SharePreferencesUtil.getString(STEP_CACHE_KEY, "");
        if (!TextUtils.isEmpty(saveData)) {
            String[] arr = saveData.split("_");
            if (arr.length != 3) {
                SharePreferencesUtil.saveString(STEP_CACHE_KEY, "");
                return;
            }
            name = arr[0];
            token = arr[1];
            String step = arr[2];
            try {
                totalSteps = Integer.parseInt(step);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadStep() {
        ArrayList<StepDataBase> dateBaseEntities = stepSaveManager.getStepsOfNoUpload(true);
        System.out.println("上传步数信息到服务器,未上传的条数:" + dateBaseEntities.size());
        for (StepDataBase stepDataBase : dateBaseEntities) {
            stepSaveManager.setStepRecordUploaded(stepDataBase);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("StepCountService:onBind");
        return stub;
    }

    @Override
    public void onDestroy() {
        saveUserData();
        unregisterReceiver(timeReceiver);
        super.onDestroy();
    }

    private void saveUserData() {
        String saveData = "default" + "_" + "defaluttoken" + "_" + totalSteps;
        SharePreferencesUtil.saveString(STEP_CACHE_KEY, saveData);
    }

    private final IStepCountInterface.Stub stub = new IStepCountInterface.Stub() {
        @Override
        public int getCurrentSteps() throws RemoteException {
            return totalSteps;
        }

        @Override
        public void setUserInfo(String name, String token) throws RemoteException {
            StepCountService.this.name = name;
            StepCountService.this.token = token;
        }
    };


}
